package com.demo.tx.seata;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.demo.miya.controller.client.SeataMiyaClient;
import com.demo.tx.dao.mapper.UserMapper;
import com.demo.tx.model.entity.User;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 测试seata分布式事务
 * @author cyj
 */
@Slf4j
@Service
public class SeataService {

    @Resource
    private SeataMiyaClient seataMiyaClient;

    @Resource
    private UserMapper userMapper;

    /**
     * 测试分布式数据插入
     * @param userId
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    public void insert(Long userId) {
        User user = new User().setUserId(userId);
        userMapper.insert(user);
    }

    /**
     * 更新抛异常
     * @param userId 用户id
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    public void updateError(Long userId) {
        User user = new User().setUserId(userId).setUserName("userName");
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, user.getUserId());
        userMapper.update(user, updateWrapper);
        throw new RuntimeException("抛异常");
    }

    /**
     * 调用第三方服务，一个服务数据插入成功，一个服务报异常
     * @param userId 用户id
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    public void insertThirdServiceError(Long userId) {
        User user = new User().setUserId(userId);
        userMapper.insert(user);

        seataMiyaClient.insert(userId);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getUserId, userId);
        log.info("userId = {}， users = {}", userId, JSON.toJSONString(userMapper.selectList(queryWrapper)));
        seataMiyaClient.insertError(userId);
    }
}
